package com.im.controller;

import com.im.service.dto.*;
import com.im.service.model.PurchasePlanVo;
import com.im.service.orgarization.smo.IOrgarizationQuerySmo;
import com.im.service.projectInfo.smo.IProjectInfoQuerySMO;
import com.im.service.purchasePlan.smo.IPurchasePlanOperSMO;
import com.im.service.purchasePlan.smo.IPurchasePlanQuerySMO;
import com.im.util.JsonUtil;
import com.im.util.ModelToVoUtil;
import com.im.util.ReturnsUtil;
import com.im.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 项目采购计划后端服务.

 * @author wangxh
 * 2018年3月21日
 */
@RestController
@RequestMapping("/purchaseService")
public class PurchaseService{

    private static final Logger logger = LogManager.getLogger(PurchaseService.class);

    @Autowired
    private IPurchasePlanQuerySMO purchasePlanQuerySMO;

    @Autowired
    private IPurchasePlanOperSMO purchasePlanOperSMO;

    @Autowired
    private IProjectInfoQuerySMO projectInfoQuerySMO;

    @Autowired
    private IOrgarizationQuerySmo orgarizationQuerySmo;

    /**
     *
     * 采购计划列表查询.
     *
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/queryPurchasePlanList")
    public String queryPurchasePlanList(@RequestBody String jsonStr){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参json:{}", jsonStr);
        }

        try {
            if (jsonStr == null || jsonStr.length() <= 0) {
                throw new BaseException("请求入参为空，请核查数据!");
            }

            PageQuery<PurchasePlan> result = purchasePlanQuerySMO.queryPurchasePlanList(jsonStr,null);
            logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(result)).toString());
            return ReturnsUtil.returnSuccess(result).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     * 查询采购计划详情.
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/queryPurchasePlanDetail")
    public String queryPurchasePlanDetail(@RequestBody PurchasePlan purchasePlan){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", purchasePlan.toString());
        }
        try {
            if (purchasePlan == null || StringUtil.isEmpty(purchasePlan.getPurchPlanId())) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            PurchasePlan result = purchasePlanQuerySMO.queryPurchasePlanDetail(purchasePlan);
            logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(result)).toString());
            return ReturnsUtil.returnSuccess(result).toString();
            } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }


    /**
     *
     *  新增采购计划信息
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addPurchasePlan")
    public String addPurchasePlan(@RequestBody PurchasePlan purchasePlan){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", purchasePlan.toString());
        }
        try {
            if (purchasePlan == null) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            purchasePlanOperSMO.addPurchasePlan(purchasePlan);
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     *  修改采购计划信息
     * @param purchasePlan
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updatePurchasePlan")
    public String updatePurchasePlan(@RequestBody PurchasePlan purchasePlan){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", purchasePlan.toString());
        }
        try {
            if (purchasePlan == null || StringUtil.isEmpty(purchasePlan.getPurchPlanId())) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            purchasePlanOperSMO.updatePurchasePlan(purchasePlan);
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     *  删除采购计划信息
     * @param purchasePlan
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/deletePurchasePlan")
    public String deletePurchasePlan(@RequestBody PurchasePlan purchasePlan){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参:{}", purchasePlan.toString());
        }
        try {
            if (purchasePlan == null || StringUtil.isEmpty(purchasePlan.getPurchPlanId())) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            purchasePlanOperSMO.deletePurchasePlan(purchasePlan);
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    /**
     *
     * 根据所属规划和项目名称查询采购计划.
     *
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/queryPurchasePlanListByCondition")
    public String queryPurchasePlanListByCondition(@RequestBody String jsonStr){
        if (logger.isInfoEnabled()) {
            logger.info("请求入参json:{}", jsonStr);
        }

        try {
            if (jsonStr == null || jsonStr.length() <= 0) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            PageQuery<PurchasePlanVo> planPageQuery = new PageQuery<PurchasePlanVo>();
            Map<String,Object> reqMap = new HashMap<String,Object>();
            JSONObject inJson = JSONObject.fromObject(jsonStr);
            if(inJson.containsKey("orgId")){
                if(null!=inJson.getString("orgId")&&!"".equals(inJson.getString("orgId"))){
                    reqMap.put("orgId",inJson.getString("orgId"));
                }
            }
            if(inJson.containsKey("planProjClass")){
                if(null!=inJson.getString("planProjClass")&&!"".equals(inJson.getString("planProjClass"))){
                    reqMap.put("planProjClass",inJson.getString("planProjClass"));
                }
            }
            if(inJson.containsKey("implProjectId")){
                if(null!=inJson.getString("implProjectId")&&!"".equals(inJson.getString("implProjectId"))){
                    reqMap.put("impleProjId",inJson.getString("implProjectId"));
                }
            }
            if(inJson.containsKey("startDt")){
                if(null!=inJson.getString("startDt")&&!"".equals(inJson.getString("startDt"))){
                    reqMap.put("startDt",inJson.getString("startDt"));
                }
            }
            if(inJson.containsKey("endDt")){
                if(null!=inJson.getString("endDt")&&!"".equals(inJson.getString("endDt"))){
                    reqMap.put("endDt",inJson.getString("endDt"));
                }
            }
            if(inJson.containsKey("statusCd")){
                if(null!=inJson.getString("statusCd")&&!"".equals(inJson.getString("statusCd"))){
                    reqMap.put("statusCd",inJson.getString("statusCd"));
                }
            }
            
            //1.根据查询条件，关联查询符合要求的采购计划。
            PageQuery<PurchasePlan> result = purchasePlanQuerySMO.queryPurchasePlanListRelated(jsonStr,reqMap);
            //3.扩展属性处理
            if(!ObjectUtils.isEmpty(result)){
                List<PurchasePlan> purchasePlans = result.getRows();
                List<PurchasePlanVo> purchasePlanVos = (List<PurchasePlanVo>)ModelToVoUtil.createVoFromModel(purchasePlans,PurchasePlanVo.class);
                for(PurchasePlanVo purchasePlanVo :purchasePlanVos){
//                    if(null!=purchasePlanVo.getImpleProjId()){
//                        ImplementProject reqObj = new ImplementProject();
//                        reqObj.setImpleProjId(purchasePlanVo.getImpleProjId());
//                        ImplementProject implementProject = projectInfoQuerySMO.queryImpleProjDetail(reqObj);
//                        if(null!=implementProject){
//                            purchasePlanVo.setImpleProjName(implementProject.getImpleProjName());
//                        }
//                    }

                    if(null!=purchasePlanVo.getAgentOrg()){
                        Orgarization reqObj = new Orgarization();
                        reqObj.setOrgId(purchasePlanVo.getAgentOrg());
                        Orgarization orgarization = orgarizationQuerySmo.queryOrgarizationDetail(reqObj);
                        if(null!=orgarization){
                            purchasePlanVo.setOrgName(orgarization.getOrgName());
                        }
                    }

                    //修改采购计划名称格式为(采购计划编号)采购计划名称
                    purchasePlanVo.setPurchPlanName("【"+purchasePlanVo.getPurchPlanNum()+"】-"+purchasePlanVo.getPurchPlanName());
                }
                planPageQuery.setTotal(result.getTotal());
                planPageQuery.setTotalPages(result.getTotalPages());
                planPageQuery.setPageSize(result.getPageSize());
                planPageQuery.setPageNumber(result.getPageNumber());
                planPageQuery.setRows(purchasePlanVos);
                return ReturnsUtil.returnSuccess(planPageQuery).toString();
            }
            logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(planPageQuery)).toString());
            return ReturnsUtil.returnSuccess(planPageQuery).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }

    
    
    
    @PostMapping(value = "/queryPurchasePlanByParam")
    public String queryPurchasePlanByParam(@RequestBody String jsonStr){
    	
    	try{
    		Map<String,Object> inMap = new HashMap<String,Object>();
        	JSONObject jo = JSONObject.fromObject(jsonStr);
        	if(jo.containsKey("purchPlanName") && !"".equals(jo.getString("purchPlanName"))){
        		inMap.put("purchPlanName", jo.getString("purchPlanName"));
        	}
        	if(jo.containsKey("impleProjId") && !"".equals(jo.getString("impleProjId"))){
        		inMap.put("impleProjId", jo.getString("impleProjId"));
        	}
        	if(jo.containsKey("purchPlanCode") && !"".equals(jo.getString("purchPlanCode"))){
        		inMap.put("purchPlanCode", jo.getString("purchPlanCode"));
        	}
        	if(jo.containsKey("purchWay") && !"".equals(jo.getString("purchWay"))){
        		inMap.put("purchWay", jo.getString("purchWay"));
        	}
        	List<PurchasePlan> list = purchasePlanQuerySMO.queryPurchasePlanByParam(inMap);
            logger.info("请求出参json:{}", JSONObject.fromObject(ReturnsUtil.returnSuccess(list)).toString());
            return ReturnsUtil.returnSuccess(list).toString();
    	} catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    	
    }

    @PostMapping(value = "/deletePurchasePlanByIds")
    public String deletePurchasePlanByIds(@RequestBody String json) throws Exception{
        try {
            Map<String,Object> reqMap = JsonUtil.getMap(json);
            if (reqMap == null) {
                throw new BaseException("请求入参为空，请核查数据!");
            }
            reqMap.put("statusCd",50);
            purchasePlanOperSMO.deletePurchasePlanByIds(reqMap);
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.getMessage()).toString();
        }
    }


    /**
     * 上传采购计划文件
     */
    @RequestMapping(value = "/uploadFileToPurchasePlan", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFileToPurchasePlan(HttpServletRequest request, @RequestBody String inJson) {
        if (logger.isInfoEnabled()) {
            logger.info("上传采购计划文件请求入参json:{}", inJson);
        }
        try {
            String result = purchasePlanOperSMO.uploadFileToPurchasePlan(inJson);
            if (logger.isInfoEnabled()) {
                logger.info("上传采购计划文件请求入参json:{}", result);
            }
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ReturnsUtil.returnException("上传采购计划文件失败！", e).toString();
        }
    }

}
